LC 312. Burst Balloons

Description

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] _ nums[i] _ nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:
You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:
Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] –> [3,5,8] –> [3,8] –> [8] –> []

coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167

Solution

Obviously, we should use DP to deal with this problem.
dp[i][j] means the maximum result we can get after bursting the ballons in the span of [i, j]

Python

1
2
3
4
5
6
7
8
9
10
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
n = len(nums)
dp = [[0] * n for _ in range(n)]
for lo in range(n - 1, -1, -1):
for hi in range(lo, n):
for i in range(lo + 1, hi):
dp[lo][hi] = max(dp[lo][hi], dp[lo][i] + dp[i][hi] + nums[hi] * nums[lo] * nums[i])
return dp[0][n - 1]

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int maxCoins(int[] iNums) {
int[] nums = new int[iNums.length + 2];
for(int i = 0; i < iNums.length; ++i) {
nums[i + 1] = iNums[i];
}
nums[0] = nums[nums.length - 1] = 1;
int n = nums.length, dp[][] = new int[n][n];
for(int k = 2; k < n; ++k) {
for(int lo = 0; lo + k < n; ++lo) {
int hi = lo + k;
for(int i = lo + 1; i < hi; ++i) {
dp[lo][hi] = Math.max(dp[lo][hi], dp[lo][i] + dp[i][hi] + nums[i] * nums[lo] * nums[hi]);
}
}
}
return dp[0][n - 1];
}
}
Donate comment here